package com.burt;

import java.io.File;
import java.io.IOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * Created by Burt on 2017/4/25 0025.
 * 自定义插件统计当前项目中的.java文件的数量
 */
@Mojo(name = "countJavaNum", defaultPhase = LifecyclePhase.PACKAGE)
public class CountFileMojo extends AbstractMojo {

    /**
     * 项目路径
     */
    @Parameter(defaultValue = "${user.dir}", property = "uri")
    private String uri;

    /**
     * 要统计的文件类型
     */
    @Parameter(defaultValue = ".java")
    private String type;

    public void execute() throws MojoExecutionException, MojoFailureException {

        System.out.println("countJavaNum plugin begin");
//        String uri = System.getProperty("user.dir");
        System.out.println("uri: " + uri);


        try {
            File inFile = new File(uri);// 要统计的项目
            int num = countFile(inFile);// 递归入口
            System.out.println("There are " + num + " " + type + " files in this directory.");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("countJavaNum plugin end");
    }

    /**
     * 统计java文件的数量
     *
     * @throws IOException
     */
    public int countFile(File inFile) {

        int num = 0;

        for (File file : inFile.listFiles()) {

            if (file.isFile() && file.getName().endsWith(type)) {//为java 文件时
                ++ num;
            } else if (file.isDirectory()) {// 当file 为目录时，递归遍历
                num += countFile(file);
            }

        }
        return num;

    }
}
